/*
 * Copyright (C),2015,北京新诺创科软件技术有限公司
 * author zhangmengliang
 */
package com.xnck.mfpms.controller;

import com.xnck.mfpms.annotation.Permission;
import com.xnck.mfpms.entity.AccountInfo;
import com.xnck.mfpms.entity.RoleInfo;
import com.xnck.mfpms.entity.UserInfo;
import com.xnck.mfpms.exception.ValidateException;
import com.xnck.mfpms.service.AccountService;
import com.xnck.mfpms.service.UserService;
import com.xnck.mfpms.util.SessionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys/org/user")
public class SysUserController extends BaseController{
    private static final Logger log = Logger.getLogger(SysUserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private AccountService accountService;

    @Permission("url_sys_org_user_list")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView getList(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new ModelAndView("/sys/org/user/list");
        return mv;
    }

    @Permission("url_sys_org_user_list")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public void postList(HttpServletRequest request, HttpServletResponse response,
                         @RequestParam(value = "uname")String userName){
        try {
            int count = userService.getsCount(userName);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("count", count);
            responseSuccessMsg(response, map, "OK");
        }
        catch (Exception e){
            log.error(e.toString());
            responseErrorMsg(response, "内部异常");
        }
    }

    @Permission("url_sys_org_user_listbody")
    @RequestMapping(value = "/listbody", method = RequestMethod.POST)
    public ModelAndView postBody(HttpServletRequest request, HttpServletResponse response,
                                 @RequestParam(value = "limit")int pageSize,
                                 @RequestParam(value = "offset")int beginIndex,
                                 @RequestParam(value = "uname")String userName,
                                 @RequestParam(value = "sort", required = false)String orderName,
                                 @RequestParam(value = "order", required = false)String orderType){
        ModelAndView mv = new ModelAndView("/sys/org/user/listbody");
        try {
            String curUserId = SessionUtils.getCurrentUserId(request);
            List<UserInfo> users = userService.gets(userName, orderName, orderType, pageSize, beginIndex);
            mv.addObject("users", users);
        }
        catch (Exception e){
            log.error(e.toString());
        }
        return mv;
    }

    /**
     * 创建用户
     * @param request
     * @param response
     * @return
     */
    @Permission("url_sys_org_user_create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView getCreate(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new ModelAndView("/sys/org/user/create");
        return mv;
    }

    /**
     * 创建用户
     * @param request
     * @param response
     * @param displayName
     * @param name
     * @param loginName
     * @param loginPwd
     * @param email
     * @param enable
     */
    @Permission("url_sys_org_user_create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public void postCreate(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "displayname")String displayName,
                           @RequestParam(value = "name")String name,
                           @RequestParam(value = "loginname")String loginName,
                           @RequestParam(value = "loginpwd")String loginPwd,
                           @RequestParam(value = "email")String email,
                           @RequestParam(value = "enable", required = false)boolean enable){
        try {
            String curUserId = SessionUtils.getCurrentUserId(request);
            userService.create(curUserId, displayName, name, loginName, loginPwd, email, enable);
            responseSuccessMsg(response, null, "添加成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 修改用户
     * @param request
     * @param response
     * @return
     */
    @Permission("url_sys_org_user_update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public ModelAndView getUpdate(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "id")String userId){
        ModelAndView mv = new ModelAndView("/sys/org/user/update");
        try {
            AccountInfo account = accountService.getWithUser(userId);
            mv.addObject("user", account.getUser());
            mv.addObject("account", account);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 修改用户
     * @param request
     * @param response
     * @param userId
     * @param displayName
     * @param name
     * @param loginPwd
     * @param email
     * @param enable
     * @return
     */
    @Permission("url_sys_org_user_update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public void postUpdate(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "id")String userId,
                           @RequestParam(value = "displayname")String displayName,
                           @RequestParam(value = "name")String name,
                           @RequestParam(value = "loginpwd")String loginPwd,
                           @RequestParam(value = "email")String email,
                           @RequestParam(value = "enable", required = false)boolean enable){
        try {
            userService.update(userId, displayName, name, loginPwd, email, enable);
            responseSuccessMsg(response, null, "修改成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 批量删除
     * @param request
     * @param response
     * @param userIds
     */
    @Permission("url_sys_org_user_multidel")
    @RequestMapping(value = "/multidel", method = RequestMethod.POST)
    public void postMulti(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam(value = "ids")String userIds){
        try {
            userService.deletes(userIds);
            responseSuccessMsg(response, null, "删除成功");
        }
        catch (Exception e){
            log.error(e.toString());
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 设置角色
     */
    @Permission("url_sys_org_user_setrole")
    @RequestMapping(value = "/setrole", method = RequestMethod.GET)
    public ModelAndView getSetRole(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "id")String userId){
        ModelAndView mv = new ModelAndView("/sys/org/user/setrole");
        try {
            UserInfo user = userService.get(userId);
            mv.addObject("user", user);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置角色
     */
    @Permission("url_sys_org_user_setrole")
    @RequestMapping(value = "/setrole", method = RequestMethod.POST)
    public void postSetRole(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "uid")String userId,
                            @RequestParam(value = "selflag", required = false)boolean isJoin,
                            @RequestParam(value = "ids")String roleIdStr){
        try {
            if (isJoin){
                userService.cancelJoinRole(userId, roleIdStr);
            }
            else {
                userService.joinRoles(userId, roleIdStr);
            }
            responseSuccessMsg(response, null, "操作成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 角色列表总数
     */
    @Permission("url_sys_org_user_rolelistcount")
    @RequestMapping(value = "/rolelistcount", method = RequestMethod.POST)
    public void postRoleList(HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(value = "selflag", required = false)boolean isJoin,
                             @RequestParam(value = "name")String roleName,
                             @RequestParam(value = "uid")String userId){
        try {
            int count;
            if (isJoin){
                count = userService.getJoinedRolesCount(userId, roleName);
            }
            else {
                count = userService.getNoJoinRolesCount(userId, roleName);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("count", count);
            responseSuccessMsg(response, map, "OK");
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }

    /**
     * 角色列表主体
     */
    @Permission("url_sys_org_user_rolelistbody")
    @RequestMapping(value = "/rolelistbody", method = RequestMethod.POST)
    public ModelAndView postRoleListBody(HttpServletRequest request, HttpServletResponse response,
                                         @RequestParam(value = "selflag", required = false)boolean isJoin,
                                         @RequestParam(value = "name")String roleName,
                                         @RequestParam(value = "uid")String userId,
                                         @RequestParam(value = "limit")int pageSize,
                                         @RequestParam(value = "offset")int beginIndex,
                                         @RequestParam(value = "sort", required = false)String orderName,
                                         @RequestParam(value = "order", required = false)String orderType){
        ModelAndView mv = new ModelAndView("/sys/org/user/rolelistbody");
        try {
            List<RoleInfo> roles;
            if (isJoin){
                roles = userService.getJoinedRoles(userId, roleName,
                        orderName, orderType, pageSize, beginIndex);
            }
            else {
                roles = userService.getNoJoinRoles(userId, roleName,
                        orderName, orderType, pageSize, beginIndex);
            }

            mv.addObject("roles", roles);
            mv.addObject("selflag", isJoin);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置菜单
     * @param request
     * @param response
     * @param userId
     * @return
     */
    @Permission("url_sys_org_user_setmenu")
    @RequestMapping(value = "/setmenu", method = RequestMethod.GET)
    public ModelAndView getSetMenu(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "id")String userId){
        ModelAndView mv = new ModelAndView("/sys/org/user/setmenu");
        try {
            UserInfo user = userService.get(userId);
            mv.addObject("user", user);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置菜单
     * @param request
     * @param response
     * @param userId
     * @param menuIdStr
     */
    @Permission("url_sys_org_user_setmenu")
    @RequestMapping(value = "/setmenu", method = RequestMethod.POST)
    public void postSetMenu(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "uid")String userId,
                            @RequestParam(value = "ids")String menuIdStr){
        try {
            userService.joinMenu(userId, menuIdStr);
            responseSuccessMsg(response, null, "关联成功");
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 菜单树
     * @param request
     * @param response
     * @param userId
     */
    @Permission("url_sys_org_user_menunodes")
    @RequestMapping(value = "/menunodes", method = RequestMethod.POST)
    public void postMenuNodes(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam(value = "id")String userId){
        try {
            List<Map<String, Object>> nodes = userService.getMenuNodes(userId);
            responseSuccessMsg(response, nodes, "ok");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }

    /**
     * 设置权限
     * @param request
     * @param response
     * @param userId
     * @return
     */
    @Permission("url_sys_org_user_setaction")
    @RequestMapping(value = "/setaction", method = RequestMethod.GET)
    public ModelAndView getSetAction(HttpServletRequest request, HttpServletResponse response,
                                     @RequestParam(value = "id")String userId){
        ModelAndView mv = new ModelAndView("/sys/org/user/setaction");
        try {
            UserInfo user = userService.get(userId);
            mv.addObject("user", user);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置权限
     * @param request
     * @param response
     * @param userId
     * @param actionIdStr
     */
    @Permission("url_sys_org_user_setaction")
    @RequestMapping(value = "/setaction", method = RequestMethod.POST)
    public void postSetAction(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam(value = "uid")String userId,
                              @RequestParam(value = "ids")String actionIdStr){
        try {
            userService.joinAction(userId, actionIdStr);
            responseSuccessMsg(response, null, "关联成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 权限树
     * @param request
     * @param response
     * @param userId
     */
    @Permission("url_sys_org_user_actionnodes")
    @RequestMapping(value = "/actionnodes", method = RequestMethod.POST)
    public void postActionNodes(HttpServletRequest request, HttpServletResponse response,
                                @RequestParam(value = "id")String userId){
        try {
            List<Map<String, Object>> nodes = userService.getActionNodes(userId);
            responseSuccessMsg(response, nodes, "ok");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }

    /**
     * 设置规则
     * @param request
     * @param response
     * @param userId
     * @return
     */
    @Permission("url_sys_org_user_setrule")
    @RequestMapping(value = "/setrule", method = RequestMethod.GET)
    public ModelAndView getSetRule(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "id")String userId){
        ModelAndView mv = new ModelAndView("/sys/org/user/setrule");
        try {
            UserInfo user = userService.get(userId);
            mv.addObject("user", user);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置规则
     * @param request
     * @param response
     * @param userId
     * @param ruleIdStr
     */
    @Permission("url_sys_org_user_setrule")
    @RequestMapping(value = "/setrule", method = RequestMethod.POST)
    public void postSetRule(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "uid")String userId,
                            @RequestParam(value = "ids")String ruleIdStr){
        try {
            userService.joinRule(userId, ruleIdStr);
            responseSuccessMsg(response, null, "关联成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 规则树
     * @param request
     * @param response
     * @param userId
     */
    @Permission("url_sys_org_user_rulenodes")
    @RequestMapping(value = "/rulenodes", method = RequestMethod.POST)
    public void postRuleNodes(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam(value = "id")String userId){
        try {
            List<Map<String, Object>> nodes = userService.getRuleNodes(userId);
            responseSuccessMsg(response, nodes, "ok");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }
}
